<template>
  <base-page-view class-name="b-share-container">
    <view class="title-block">
      <view class="main">图片选择</view>
      <view class="sub">（已选择1张）</view>
    </view>
    <horizontalList ref="image-list" from-sourch="home" list-name="image" :click-emit-index="0" :list="imageList" @itemClick="handleImageClick">
      <template v-slot="{item, index}">
        <b-image class-name="image" :src="item.pic" mode="aspectFit" />
        <b-image v-if="item.checked" class-name="icon" :src="checkedIcon" mode="aspectFit" />
        <b-image v-else class-name="icon" :src="checkIcon" mode="aspectFit" />
        <view v-if="codeImgIndex === index" class="text">二维码推广图</view>
      </template>
    </horizontalList>
    <view class="title-block">
      <view>分享文案</view>
    </view>
    <view v-if="shareContent.goodsInfo && shareContent.goodsInfo.length" class="content-block">
      <view v-for="(item, index) in shareContent.goodsInfo" :key="index">{{ item }}</view>
      <template v-if="shareTypeList[1].checked">
        <view>【下载链接】https://a.app.qq.com/o/simple.jsp?pkgname=com.bisinuolan.app</view>
        <view>【官方邀请码】{{ userInfo.invite_code }}</view>
      </template>
      <template v-if="shareTypeList[0].checked">
        <view>——————————————</view>
        <view>{{ shareContent.shareGoodsUrl }}</view>
      </template>
    </view>
    <view class="type-block">
      <view v-for="(item, index) in shareTypeList" :key="index" class="type-item" @click="changeType(index)">
        <b-image v-if="item.checked" class-name="icon" :src="checkedIcon" mode="aspectFit" />
        <b-image v-else class-name="icon" :src="checkIcon" mode="aspectFit" />
        {{ item.text }}
      </view>
    </view>
    <footer-bar>
      <view class="btn-block">
        <view class="btn" @click="copy">复制分享文案</view>
        <view class="btn btn-img" @click="downloadImg">分享图片（{{ imageList.filter(i => i.checked).length }}）</view>
      </view>
    </footer-bar>
  </base-page-view>
</template>
<script>
import { mapState } from 'vuex'
import HorizontalList from '@/components/horizontalList/index'
import FooterBar from '@/components/footerBar'
import { setClipboardData } from '@/utils/tools'
import './index.scss'
export default {
  name: 'BShare',
  components: {
    HorizontalList,
    FooterBar
  },
  data() {
    return {
      loading: true,
      codeImgIndex: 0,
      imageList: [],
      linkQuery: {},
      shareContent: {
        goodsInfo: []
      },
      shareText: '',
      shareTypeList: [
        { text: '购买链接', checked: true },
        { text: '邀请下载', checked: false }
      ],

      checkIcon: `${process.env.VUE_APP_IMAGE_ASSET}/images/biHuaSuan/icon_check.png`,
      checkedIcon: `${process.env.VUE_APP_IMAGE_ASSET}/images/biHuaSuan/icon_checked.png`
    }
  },
  computed: {
    ...mapState([
      'userInfo'
    ]),
    copyText() {
      let result = this.shareText
      if (this.shareTypeList[1].checked) {
        result += `【下载链接】https://a.app.qq.com/o/simple.jsp?pkgname=com.bisinuolan.app\n【官方邀请码】${this.userInfo.invite_code}\n`
      }
      if (this.shareTypeList[0].checked) {
        result += `——————————————\n${this.shareContent.shareGoodsUrl}`
      }
      return result
    }
  },
  onLoad(options) {
    this.query = { ...options }
    this.fetchData()
  },
  methods: {
    async fetchData() {
      this.loading = true
      const res = await this.$api.biHuaSuanApi.getGoodsDetail(this.query)
      if (res.success && res.data) {
        const { slideImageUrls, goodsId, title, actualPrice, commission, couponLink, hasCoupon, imageUrl, originalPrice, platform } = res.data
        this.imageList = (slideImageUrls ? slideImageUrls.split(',') : []).map((i, index) => ({ pic: i, checked: index === 0 }))
        this.linkQuery = {
          goodsId: goodsId,
          title: title,
          actualPrice: actualPrice,
          commission: commission,
          couponLink: couponLink || '',
          hasCoupon: hasCoupon,
          imageUrl: imageUrl,
          originalPrice: originalPrice,
          platform: platform,
          inviteCode: this.userInfo ? this.userInfo.invite_code : ''
        }
        this.fetchLinkData()
      }
    },
    // 去拼多多授权
    toAuthPdd (data) {
      this.$gc.$message({
          title: '提 示',
          content: '请先前往拼多多进行授权',
          confirmText: '去授权',
          align: 'center',
          confirm: () => {
            // #ifdef H5
            window.open(data.h5AppOauthUrl, '_blank')
            // #endif
            // #ifdef MP-WEIXIN
            uni.navigateToMiniProgram({
                appId: data.weAppInfo.appId,
                path: data.miniOauthUrl,
            })
            // #endif
          }
        })
    },
    async fetchLinkData() {
      const res = await this.$api.biHuaSuanApi.getShareUrl(this.linkQuery)
      if(res.success && res.data.hasOauth===0 && res.data.platform === "PDD" ){
        this.toAuthPdd(res.data)
        this.loading = false
        return
      }
      if (res.success && res.data) {
        const { goodsInfo } = res.data.shareContent
        this.shareText = goodsInfo
        this.shareContent = {
          ...res.data.shareContent,
          goodsInfo: goodsInfo ? goodsInfo.split('\n') : []
        }
      }
      this.loading = false
    },
    handleImageClick(index) {
      // this.$refs['image-list'].setIndex(index)
      if (this.imageList[index].checked) {
        if (this.imageList.filter(i => i.checked).length > 1) {
          this.imageList[index].checked = false
          if (this.codeImgIndex === index) {
            this.codeImgIndex = this.imageList.findIndex(i => i.checked)
          }
        } else {
          uni.showToast({
            title: '至少选择一张图片',
            icon: 'none'
          })
        }
      } else {
        this.imageList[index].checked = true
      }
    },
    changeType(index) {
      if (this.shareTypeList[index].checked) {
        if (this.shareTypeList.filter(i => i.checked).length > 1) {
          this.shareTypeList[index].checked = false
        } else {
          uni.showToast({
            title: '至少选择一项分享文案',
            icon: 'none'
          })
        }
      } else {
        this.shareTypeList[index].checked = true
      }
    },
    copy() {
      setClipboardData({
        data: this.copyText,
        success: () => {
          uni.showToast({
            title: '文案已复制成功',
            icon: 'none',
            duration: 1500
          })
        }
      })
    },
    downloadImg() {
      var image = new Image()
      // 解决跨域 Canvas 污染问题
      image.setAttribute('crossOrigin', 'anonymous')
      image.onload = function() {
        var canvas = document.createElement('canvas')
        canvas.width = image.width
        canvas.height = image.height

        var context = canvas.getContext('2d')
        context.drawImage(image, 0, 0, image.width, image.height)
        var url = canvas.toDataURL('image/png')

        // 生成一个a元素
        var a = document.createElement('a')
        // 创建一个单击事件
        var event = new MouseEvent('click')

        // 将a的download属性设置为我们想要下载的图片名称，若name不存在则使用‘下载图片名称’作为默认名称
        a.download = name || '下载图片名称'
        // 将生成的URL设置为a.href属性
        a.href = url

        // 触发a的单击事件
        a.dispatchEvent(event)
      }

      image.src = this.imageList[0].pic
      /* uni.downloadFile({
        url: this.imageList[0].pic, // 仅为示例，并非真实的资源
        success: (res) => {
          if (res.statusCode === 200) {
            uni.saveFile({
              tempFilePath: res.tempFilePath,
              success: (result) => {
                console.log('下载成功', result)
              }
            })
          }
        }
      }) */
    }
  }
}
</script>
